const jwt = require('jsonwebtoken')
// , koajwt = require('koa-jwt');
// 验证函数

// token权限拦截
// app.use(koajwt({
//     secret: 'anlin'
// }).unless({
//     path: [/\/sign/]
// }));


const util = require('../../util/index.js')
const { User } = require('../../router/schema')

module.exports = (app) => {
  app.use(async (ctx, next) => {
    if (ctx.request.url.match('sign')) {
      await next()
    } else if (ctx.request.url.includes('.')) {
      await next()
    } else {
      const authorization = ctx.request.header.authorization;
      if (authorization) {
        const verFlog = util.checkUndefined([
          {
            token: authorization,
            type: 'string',
            label: 'token'
          }
        ]);
        if (verFlog) {
          const token = authorization.split(' ')[1]
          await jwt.verify(token, 'anlin', async (error, result) => {
            if (error) {
              return ctx.body = {
                code: -201,
                data: null,
                msg: 'token验证失败'
              }
            }

            const yz = async (num) => {
              const _id = result._id;
              await User.findOne({ _id }).then(async res => {
                if (res) {
                  if (res.role === num) {
                    await next()
                  } else {
                    ctx.body = {
                      code: -201,
                      data: null,
                      msg: 'role权限不足'
                    }
                  }
                } else {
                  ctx.body = {
                    code: -401,
                    data: null,
                    msg: 'token失效'
                  }
                }
              })
            }

            if (ctx.request.url.match('admin')) {
              await yz(100)
            } else {
              await yz(10)
            }
          })
        } else {
          ctx.body = {
            code: -101,
            data: null,
            msg: 'token验证失败'
          }
        }
      } else {
        ctx.body = {
          code: -201,
          data: null,
          msg: '没有token'
        }
      }
    }
  })
}